package cn.cool.domain.trade.service.settlement.filter;

import cn.cool.domain.trade.adapter.repository.ITradeRepository;
import cn.cool.domain.trade.model.entity.GroupBuyTeamEntity;
import cn.cool.domain.trade.model.entity.MarketPayOrderEntity;
import cn.cool.domain.trade.model.entity.TradeSettlementRuleCommandEntity;
import cn.cool.domain.trade.model.entity.TradeSettlementRuleFilterBackEntity;
import cn.cool.domain.trade.service.settlement.factory.TradeSettlementRuleFilterFactory;
import cn.cool.types.design.framework.link.model2.handler.ILogicHandler;
import cn.cool.types.enums.ResponseCode;
import cn.cool.types.exception.AppException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

@Service
@Slf4j
public class SettableRuleFilter
        implements ILogicHandler<TradeSettlementRuleCommandEntity, TradeSettlementRuleFilterFactory.DynamicContext, TradeSettlementRuleFilterBackEntity> {
    @Resource
    private ITradeRepository repository;

    @Override
    public TradeSettlementRuleFilterBackEntity apply(TradeSettlementRuleCommandEntity requestParameter, TradeSettlementRuleFilterFactory.DynamicContext dynamicContext) throws Exception {
        log.info("结算规则过滤-渠道黑名单校验：{} outTradeNo: {}", requestParameter.getUserId(), requestParameter.getOutTradeNo());

        MarketPayOrderEntity marketPayOrderEntity = dynamicContext.getMarketPayOrderEntity();
        //查询拼团信息
        GroupBuyTeamEntity groupBuyTeamEntity = repository.queryGroupBuyTeamByTeamId(marketPayOrderEntity.getTeamId());

        Date outTradeTime = requestParameter.getOutTradeTime();
        if (!outTradeTime.before(groupBuyTeamEntity.getValidEndTime())) {
            throw new AppException(ResponseCode.E0106);
        }

        dynamicContext.setGroupBuyTeamEntity(groupBuyTeamEntity);
        return next(requestParameter, dynamicContext);
    }
}
